package com.kb.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class TokenUtil {
    /**
     * 设置延期的时间 x分钟
     * x*1000*60
     */
//    private static final long EXPIR_DATE = 60000;
    private static final long EXPIR_DATE = 3600000; //1小时

    /**
     * 设置token的秘钥
     */
    private static final String TOKEN_SECRET = "kb_resource_qwe12300czx";


    /**
     * 获取token
     *
     * @param userName
     * @param passWord
     * @return
     */
    public static String getTokenSecret(String userName, String passWord) {
        String token = "";
        try {
            // 过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIR_DATE);
            // 设置头部信息
            Map<String, Object> head = new HashMap<>();
            head.put("typ", "JWT");
            head.put("alg", "HS256");

            // 设置秘钥
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

//            JWT.create().setHeader()
            // 生成签名

            token = JWT.create()
                    .withHeader(head)
                    .withClaim("userName", userName)
                    .withClaim("passWord", passWord)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
        return token;
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            return verifier.verify(token);
    }
    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public static String getUserNameFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("token");
        DecodedJWT decodedJWT = verify(bearerToken);
        return decodedJWT.getClaim("userName").asString();
    }
}
